package org.ceteca.explica.server.common;

import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;

import org.ceteca.explica.core.InterfaceExplica;
import org.ceteca.explica.core.common.CommonManager;
import org.ceteca.explica.core.management.InterfaceManagement;
import org.ceteca.explica.core.ssl.RMISSLClientSocketFactory;
import org.ceteca.explica.core.ssl.RMISSLServerSocketFactory;
import org.ceteca.explica.core.util.LoggerFactory;
import org.ceteca.explica.server.ServerContext;

public class CommonManagerBuilder {
	/**
	 * Initializes the common manager remote object. Makes the registration and
	 * binding of the remote CommonManager service.  
	 */
	public static void initCommonManager() {
		if (System.getSecurityManager() == null) {
            System.setSecurityManager(new SecurityManager());
        }
        try {
            String name = InterfaceExplica.JNDI_COMMON_MANAGER_EXPORT_NAME;
            CommonManagerImpl manager = new CommonManagerImpl();
            
            UnicastRemoteObject.unexportObject(manager, true);
            System.out.println("CommonManager unexported");


            /**
             * Export the CommonManager object to listen in the assigned port
             */
            CommonManager stub =
                (CommonManager) UnicastRemoteObject.exportObject(manager, InterfaceExplica.RMI_COMMON_MANAGER_EXPORT_PORT, 
                		new RMISSLClientSocketFactory(),
               		 	new RMISSLServerSocketFactory());
            
            System.out.println("CommonManager exported");

            /*
    	     * Create a registry and bind stub in registry.
    	     */
//    	    LocateRegistry.createRegistry(InterfaceExplica.RMI_REGISTRY_PORT);
    	    Registry registry = LocateRegistry.getRegistry(InterfaceExplica.RMI_REGISTRY_PORT);
    	    
            System.out.println("Registry located");
            registry.rebind(name, stub);
            System.out.println("CommonManager bound");
        } catch (Exception e) {
            System.err.println("CommonManager exception:");
            e.printStackTrace();
        }
        // Init the logger service
		System.out.println("LOGGING CONFIGURATION PATH= " + ServerContext.getInstance().getClass().getResource(InterfaceExplica.COMMON_LOG_CONFIG_FILE).getPath());
		LoggerFactory.initLogger(
				InterfaceExplica.EXPLICA_LOG_DIR,
				ServerContext.getInstance().getClass().getResourceAsStream(InterfaceExplica.COMMON_LOG_CONFIG_FILE));
	
        
	}
}
